Security News
Python Overtakes JavaScript as Top Programming Language on GitHub
Python becomes GitHub's top language in 2024, driven by AI and data science projects, while AI-powered security tools are gaining adoption.
rehype-parse
Advanced tools
rehype-parse is a plugin for the unified processor that parses HTML into a syntax tree. It is part of the rehype ecosystem, which is a toolset for transforming HTML with plugins. This package is particularly useful for processing and manipulating HTML content programmatically.
Basic HTML Parsing
This feature allows you to parse a simple HTML string into a syntax tree. The code sample demonstrates how to parse an HTML string and inspect the resulting tree structure.
const unified = require('unified');
const parse = require('rehype-parse');
const inspect = require('unist-util-inspect');
const html = '<h1>Hello, world!</h1>';
const tree = unified()
.use(parse)
.parse(html);
console.log(inspect(tree));
Parsing with Options
This feature allows you to parse HTML with specific options. In this example, the 'fragment' option is set to true, which allows parsing of HTML fragments instead of full documents.
const unified = require('unified');
const parse = require('rehype-parse');
const inspect = require('unist-util-inspect');
const html = '<h1>Hello, world!</h1>';
const tree = unified()
.use(parse, { fragment: true })
.parse(html);
console.log(inspect(tree));
Integration with Other Plugins
This feature demonstrates how to integrate rehype-parse with other plugins in the rehype ecosystem. The code sample shows how to parse HTML and then stringify it back to HTML.
const unified = require('unified');
const parse = require('rehype-parse');
const stringify = require('rehype-stringify');
const html = '<h1>Hello, world!</h1>';
const output = unified()
.use(parse)
.use(stringify)
.processSync(html)
.toString();
console.log(output);
htmlparser2 is a fast and forgiving HTML/XML parser. It is more low-level compared to rehype-parse and provides a SAX-style parser, which can be more complex to use but offers more control over the parsing process.
parse5 is a highly compliant HTML parser that closely follows the WHATWG HTML specification. It is similar to rehype-parse in terms of compliance and ease of use but is a standalone parser without the plugin ecosystem that rehype offers.
jsdom is a JavaScript implementation of the DOM and HTML standards. It is more heavyweight compared to rehype-parse and is used for simulating a browser environment, making it suitable for more complex DOM manipulations and testing.
rehype plugin to add support for parsing HTML input.
This package is a unified (rehype) plugin that defines how to take HTML as input and turn it into a syntax tree. When it’s used, HTML can be parsed and other rehype plugins can be used after it.
See the monorepo readme for info on what the rehype ecosystem is.
This plugin adds support to unified for parsing HTML.
You can alternatively use rehype
instead, which combines
unified, this plugin, and rehype-stringify
.
When you’re in a browser, trust your content, don’t need positional info, and
value a smaller bundle size, you can use rehype-dom-parse
instead.
This plugin is built on parse5
and
hast-util-from-parse5
, which deal with HTML-compliant
tokenizing, parsing, and creating nodes.
rehype focusses on making it easier to transform content by abstracting such
internals away.
This package is ESM only. In Node.js (version 12.20+, 14.14+, or 16.0+), install with npm:
npm install rehype-parse
In Deno with esm.sh
:
import rehypeParse from 'https://esm.sh/rehype-parse@8'
In browsers with esm.sh
:
<script type="module">
import rehypeParse from 'https://esm.sh/rehype-parse@8?bundle'
</script>
Say we have the following module example.js
:
import {unified} from 'unified'
import rehypeParse from 'rehype-parse'
import rehypeRemark from 'rehype-remark'
import remarkStringify from 'remark-stringify'
main()
async function main() {
const file = await unified()
.use(rehypeParse)
.use(rehypeRemark)
.use(remarkStringify)
.process('<h1>Hello, world!</h1>')
console.log(String(file))
}
…running that with node example.js
yields:
# Hello, world!
This package exports no identifiers.
The default export is rehypeParse
.
unified().use(rehypeParse[, options])
Add support for parsing HTML input.
options
Configuration (optional).
options.fragment
Specify whether to parse as a fragment (boolean
, default: false
).
The default is to expect a whole document.
In document mode, unopened html
, head
, and body
elements are opened.
options.space
Which space the document is in ('svg'
or 'html'
, default: 'html'
).
When an <svg>
element is found in the HTML space, rehype-parse
already
automatically switches to and from the SVG space when entering and exiting it.
👉 Note: rehype is not an XML parser. It supports SVG as embedded in HTML. It does not support the features available in XML. Passing SVG files might break but fragments of modern SVG should be fine.
👉 Note: make sure to set
fragment: true
ifspace: 'svg'
.
options.emitParseErrors
Emit HTML parse errors as warning messages
(boolean
, default: false
).
Specific rules can be turned off by setting their IDs in options
to false
(or 0
).
The default, when emitParseErrors: true
, is true
(or 1
), and means that
rules emit as warnings.
Rules can also be configured with 2
, to turn them into fatal errors.
The list of parse errors:
abandonedHeadElementChild
— unexpected metadata element after head (example)abruptClosingOfEmptyComment
— unexpected abruptly closed empty comment (example)abruptDoctypePublicIdentifier
— unexpected abruptly closed public identifier (example)abruptDoctypeSystemIdentifier
— unexpected abruptly closed system identifier (example)absenceOfDigitsInNumericCharacterReference
— unexpected non-digit at start of numeric character reference (example)cdataInHtmlContent
— unexpected CDATA section in HTML (example)characterReferenceOutsideUnicodeRange
— unexpected too big numeric character reference (example)closingOfElementWithOpenChildElements
— unexpected closing tag with open child elements (example)controlCharacterInInputStream
— unexpected control character (example)controlCharacterReference
— unexpected control character reference (example)disallowedContentInNoscriptInHead
— disallowed content inside <noscript>
in <head>
(example)duplicateAttribute
— unexpected duplicate attribute (example)endTagWithAttributes
— unexpected attribute on closing tag (example)endTagWithTrailingSolidus
— unexpected slash at end of closing tag (example)endTagWithoutMatchingOpenElement
— unexpected unopened end tag (example)eofBeforeTagName
— unexpected end of file (example)eofInCdata
— unexpected end of file in CDATA (example)eofInComment
— unexpected end of file in comment (example)eofInDoctype
— unexpected end of file in doctype (example)eofInElementThatCanContainOnlyText
— unexpected end of file in element that can only contain text (example)eofInScriptHtmlCommentLikeText
— unexpected end of file in comment inside script (example)eofInTag
— unexpected end of file in tag (example)incorrectlyClosedComment
— incorrectly closed comment (example)incorrectlyOpenedComment
— incorrectly opened comment (example)invalidCharacterSequenceAfterDoctypeName
— invalid sequence after doctype name (example)invalidFirstCharacterOfTagName
— invalid first character in tag name (example)misplacedDoctype
— misplaced doctype (example)misplacedStartTagForHeadElement
— misplaced <head>
start tag (example)missingAttributeValue
— missing attribute value (example)missingDoctype
— missing doctype before other content (example)missingDoctypeName
— missing doctype name (example)missingDoctypePublicIdentifier
— missing public identifier in doctype (example)missingDoctypeSystemIdentifier
— missing system identifier in doctype (example)missingEndTagName
— missing name in end tag (example)missingQuoteBeforeDoctypePublicIdentifier
— missing quote before public identifier in doctype (example)missingQuoteBeforeDoctypeSystemIdentifier
— missing quote before system identifier in doctype (example)missingSemicolonAfterCharacterReference
— missing semicolon after character reference (example)missingWhitespaceAfterDoctypePublicKeyword
— missing whitespace after public identifier in doctype (example)missingWhitespaceAfterDoctypeSystemKeyword
— missing whitespace after system identifier in doctype (example)missingWhitespaceBeforeDoctypeName
— missing whitespace before doctype name (example)missingWhitespaceBetweenAttributes
— missing whitespace between attributes (example)missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers
— missing whitespace between public and system identifiers in doctype (example)nestedComment
— unexpected nested comment (example)nestedNoscriptInHead
— unexpected nested <noscript>
in <head>
(example)nonConformingDoctype
— unexpected non-conforming doctype declaration (example)nonVoidHtmlElementStartTagWithTrailingSolidus
— unexpected trailing slash on start tag of non-void element (example)noncharacterCharacterReference
— unexpected noncharacter code point referenced by character reference (example)noncharacterInInputStream
— unexpected noncharacter character (example)nullCharacterReference
— unexpected NULL character referenced by character reference (example)openElementsLeftAfterEof
— unexpected end of file (example)surrogateCharacterReference
— unexpected surrogate character referenced by character reference (example)surrogateInInputStream
— unexpected surrogate characterunexpectedCharacterAfterDoctypeSystemIdentifier
— invalid character after system identifier in doctype (example)unexpectedCharacterInAttributeName
— unexpected character in attribute name (example)unexpectedCharacterInUnquotedAttributeValue
— unexpected character in unquoted attribute value (example)unexpectedEqualsSignBeforeAttributeName
— unexpected equals sign before attribute name (example)unexpectedNullCharacter
— unexpected NULL character (example)unexpectedQuestionMarkInsteadOfTagName
— unexpected question mark instead of tag name (example)unexpectedSolidusInTag
— unexpected slash in tag (example)unknownNamedCharacterReference
— unexpected unknown named character reference (example)options.verbose
Add extra positional info (boolean
, default: false
).
The following example shows the difference between parsing as a document and parsing as a fragment:
import {unified} from 'unified'
import rehypeParse from 'rehype-parse'
import rehypeStringify from 'rehype-stringify'
main()
async function main() {
const doc = '<title>Hi!</title><h1>Hello!</h1>'
console.log(
String(
await unified()
.use(rehypeParse, {fragment: true})
.use(rehypeStringify)
.process(doc)
)
)
console.log(
String(
await unified()
.use(rehypeParse, {fragment: false})
.use(rehypeStringify)
.process(doc)
)
)
}
…yields:
<title>Hi!</title><h1>Hello!</h1>
<html><head><title>Hi!</title></head><body><h1>Hello!</h1></body></html>
👉 Note: observe that when a whole document is expected (second example), missing elements are opened and closed.
<html>
The following example shows how whitespace is handled when around and directly
inside the <html>
element:
import {unified} from 'unified'
import rehypeParse from 'rehype-parse'
import rehypeStringify from 'rehype-stringify'
main(`<!doctype html>
<html lang=en>
<head>
<title>Hi!</title>
</head>
<body>
<h1>Hello!</h1>
</body>
</html>`)
async function main(doc) {
console.log(
String(await unified().use(rehypeParse).use(rehypeStringify).process(doc))
)
}
…yields (where ␠
represents a space character):
<!doctype html><html lang="en"><head>
<title>Hi!</title>
</head>
<body>
<h1>Hello!</h1>
␠␠
</body></html>
👉 Note: observe that the line ending before
<html>
is ignored, the line ending and two spaces before<head>
is moved inside it, and the line ending after</body>
is moved before it.
This behavior is described by the HTML standard (see the section 13.2.6.4.1 “The ‘initial’ insertion mode” and adjacent states) which rehype follows.
The changes to this meaningless whitespace should not matter, except when
formatting markup, in which case rehype-format
can be used to
improve the source code.
The following example shows how HTML parse errors can be enabled and configured:
import {reporter} from 'vfile-reporter'
import {unified} from 'unified'
import rehypeParse from 'rehype-parse'
import rehypeStringify from 'rehype-stringify'
main()
async function main() {
const file = await unified()
.use(rehypeParse, {
emitParseErrors: true, // Emit all.
missingWhitespaceBeforeDoctypeName: 2, // Mark one as a fatal error.
nonVoidHtmlElementStartTagWithTrailingSolidus: false // Ignore one.
})
.use(rehypeStringify)
.process(`<!doctypehtml>
<title class="a" class="b">Hello…</title>
<h1/>World!</h1>`)
console.log(reporter(file))
}
…yields:
1:10-1:10 error Missing whitespace before doctype name missing-whitespace-before-doctype-name parse-error
2:23-2:23 warning Unexpected duplicate attribute duplicate-attribute parse-error
2 messages (✖ 1 error, ⚠ 1 warning)
🧑🏫 Info: messages in unified are warnings instead of errors. Other linters (such as ESLint) almost always use errors. Why? Those tools only check code style. They don’t generate, transform, and format code, which is what rehype and unified focus on, too. Errors in unified mean the same as an exception in your JavaScript code: a crash. That’s why we use warnings instead, because we continue checking more HTML and continue running more plugins.
HTML is parsed according to WHATWG HTML (the living standard), which is also followed by browsers such as Chrome and Firefox.
The syntax tree format used in rehype is hast.
This package is fully typed with TypeScript.
The extra types Options
, ErrorCode
, and ErrorSeverity
are exported.
Projects maintained by the unified collective are compatible with all maintained versions of Node.js. As of now, that is Node.js 12.20+, 14.14+, and 16.0+. Our projects sometimes work with older versions, but this is not guaranteed.
As rehype works on HTML, and improper use of HTML can open you up to a
cross-site scripting (XSS) attack, use of rehype can also be unsafe.
Use rehype-sanitize
to make the tree safe.
Use of rehype plugins could also open you up to other attacks. Carefully assess each plugin and the risks involved in using them.
For info on how to submit a report, see our security policy.
See contributing.md
in rehypejs/.github
for ways
to get started.
See support.md
for ways to get help.
This project has a code of conduct. By interacting with this repository, organization, or community you agree to abide by its terms.
Support this effort and give back by sponsoring on OpenCollective!
Vercel |
Motif |
HashiCorp |
GitBook |
Gatsby | ||||
Netlify |
Coinbase |
ThemeIsle |
Expo |
Boost Note |
Markdown Space |
Holloway | ||
You? |
FAQs
rehype plugin to parse HTML
The npm package rehype-parse receives a total of 602,320 weekly downloads. As such, rehype-parse popularity was classified as popular.
We found that rehype-parse demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Python becomes GitHub's top language in 2024, driven by AI and data science projects, while AI-powered security tools are gaining adoption.
Security News
Dutch National Police and FBI dismantle Redline and Meta infostealer malware-as-a-service operations in Operation Magnus, seizing servers and source code.
Research
Security News
Socket is tracking a new trend where malicious actors are now exploiting the popularity of LLM research to spread malware through seemingly useful open source packages.